//app.js
//全局极光IM
let JMessage = require('./utils/jmessage-wxapplet-sdk-1.4.3.min')
const utils = require('./utils/util.js')
App({
  onLaunch: function () {
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    let _this = this
    wx.getSystemInfo({
      success: res => {
        let modelmes = res.model;
        // console.log(res.model)
        let iphoneArr = ['iPhone X', 'iPhone 11', 'iPhone 11 Pro Max']
        iphoneArr.forEach(function (item) {
          if (modelmes.search(item) != -1) {
            _this.globalData.isIphoneX = true
          }
        })    
      }
    })
    let jim = new JMessage({});
    this.globalData.jim = jim;
    var that = this;
    //应用初始化JMessage
    this.IMInit();
    //断线监听
    this.globalData.jim.onDisconnect(function(){
      that.IMInit()
    });
  },
  onShow:function () {
     
  },
  //jim初始化
  IMInit:function(){
    let that = this;
    //获取jim四要素
    utils.requestUrl({
      url:'/niu/apiv3/member_jmauth.php',
      params: {
        markid:wx.getStorageSync('markId')
      }
    }).then((res) =>{
      let data = res.data;
      // console.log(data);
      let userName = data.imid;
      let passWord = data.impw;

      //im初始化
      this.globalData.jim.init({
        "appkey": data.appkey,
        "random_str": data.random_str,
        "signature": data.signature,
        "timestamp": data.timestamp,
        "flag": 1
      }).onSuccess(function (data) {
        // console.log(data)
        //调用登录
        that.IMLogin(userName,passWord);
      }).onFail(function (data) {
        that.IMInit();
      });
    })
  },
  //im登录
  IMLogin: function (userName,passWord) {
    let that = this;
    this.globalData.jim.login({
      'username': userName,
      'password': passWord
    }).onSuccess(function (data) {
      // console.log(data);
      //获取离线消息
      that.globalData.jim.onSyncConversation(function(data) {
        // console.log(data);
        // that.globalData.onSyncConversation = data;
        // 缓存离线消息
        for(var i = 0;i < data.length;i++){
          wx.setStorageSync(data[i].from_username, data[i].msgs)
        }
      })
    }).onFail(function (data) {
      utils.toast('消息系统登录失败,请重新登录')
    }).onTimeout(function (data) {
      utils.toast('消息系统登录超时,请重新登录')
    });
  },
  globalData: {
    userInfo: null,
    jim:null,
    url:'https://api.odancool.com',
    urlView:'https://api.odancool.com/weixinapp/view/',
    onSyncConversation:null
  }
})